# -*- coding: utf-8 -*-
# @#Time : 2021/8/20 9:47

# @File : gdtv_play_source.py
# @Software : PyCharm
import base64
import hmac
import json
import time
from hashlib import sha256

import httpx as httpx

import schedule_tool


# import requests as requests


def get_millis():
    """

    :rtype: str
    """
    return str(round(time.time() * 1000))


def encrypt(data: bytes = None, encrypt_key: bytes = None) -> str:
    """

    :rtype: str
    """
    signature = base64.b64encode(hmac.new(encrypt_key, data, digestmod=sha256).digest())
    return signature.decode("utf-8")


def build_m3u_data(logo: str, category: str, channel_name: str, play_url: str):
    channel_data = '#EXTINF:-1,  tvg-logo="{}", group-title="{}", {}\n{}\n'.format(logo,
                                                                                   category,
                                                                                   channel_name,
                                                                                   play_url)
    return channel_data


class GdtvSource:
    def __init__(self, blacklist: list):
        self.ca_key = '89541443007807288657755311869534'
        self.time_now = get_millis()
        self.blacklist = blacklist

    def get_ca_signature(self, url):
        encrypt_key = 'dfkcY1c3sfuw0Cii9DWjOUO3iQy2hqlDxyvDXd1oVMxwYAJSgeB6phO8eW1dfuwX'.encode('utf-8')

        unencrypted_str = ("GET\n" + url + "\n" + self.time_now + "\n").encode('utf-8')
        return encrypt(data=unencrypted_str, encrypt_key=encrypt_key)

    def bloccker(self, item):
        """
        :rtype: int
        """
        counter = 0
        for block in self.blacklist:
            if item.find(block) != -1:
                counter = -1
                # print(item)
            else:
                continue
        # print(counter)
        return counter

    @staticmethod
    def filter(f_item):
        if f_item == 1:
            category = '广播'
        else:
            category = '地方频道'
        return category

    def parse_channel(self, channel_list):
        data = []
        for channel in channel_list:
            # print(type(channel['name']))
            if self.bloccker(channel['name']) == 0:
                logo = channel['coverUrl']
                category = self.filter(channel['category'])
                channel_name = channel['name']
                play_url = json.loads(
                    channel['playUrl'])[
                    'hd']

                # channel_data = '#EXTINF:-1, tvg-logo="{}", group-title="{}", {} \n{}\n'.format(channel['coverUrl'],
                #                                                                                self.filter(
                #                                                                                    channel['category']),
                #                                                                                channel['name'],
                #                                                                                json.loads(
                #                                                                                    channel['playUrl'])[
                #                                                                                    'hd'])

                channel_data = build_m3u_data(logo=logo, category=category, channel_name=channel_name,
                                              play_url=play_url)

                data.append(channel_data)
                # print(channel['coverUrl'])  # 由于默认台标毫无辨析度，使用大封面作为台标
                # print(channel['name'])
                # print(json.loads(channel['playUrl'])['hd'])
                # # pass
            else:
                continue
        return data

    def get_channel(self):
        source_json_url = "https://gdtv-api.gdtv.cn/api/tv/v1/tvChannel"
        ca_signature = self.get_ca_signature(source_json_url)
        headers = {

            'x-itouchtv-ca-key': self.ca_key,
            'x-itouchtv-ca-signature': ca_signature,
            'x-itouchtv-ca-timestamp': self.time_now,

            'x-itouchtv-client': 'WEB_PC',
            'x-itouchtv-device-id': 'WEB_a9287ef0-018e-11ec-aab9-65891e10b97a',
            'origin': 'https://www.gdtv.cn/',
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.164 Safari/537.36'

        }

        with httpx.Client(headers=headers, http2=True) as client:
            get_channel = client.get(url=source_json_url)
            # opinion_channel = client.options(url=source_json_url)

            channel_dict = json.loads(get_channel.content.decode())
            # print(channel_dict)
        data = self.parse_channel(channel_dict)

        # self.write_file(data)
        return data
        # print(json.dumps(channel_dict))


def output():
    blacklist = ['购', '房']
    gdtvs = GdtvSource(blacklist)
    schedule_tool.schedule_process('gdtv_source.m3u', gdtvs.get_channel())


if __name__ == '__main__':
    output()
